package com.letu.aopcache.model;

import lombok.Data;

import java.io.Serializable;
import java.util.List;
import java.util.Map;

/**
 * 对缓存数据进行封装(全量数据)
 */
@Data
public class CacheWrapper<T> implements Serializable, Cloneable {

    private static final long serialVersionUID = 1L;

    /**
     * 缓存接口结果数据
     */
    private T cacheObject;

    /**
     * 最后加载时间
     * 当最后加载时间小于重启时间，则删除hash类型的缓存
     */
    private long lastLoadTime;

    /**
     * 缓存时长
     */
    private int expire;

    /**
     * 返回结果类型
     */
    private Class<?> returnType;

    /**
     * 结果id集合
     */
    private List<Long> ids;

    /**
     * 实体结果集合
     */
    private List<Object> objectList;
    /**
     * 实体结果类名称
     */
    private String objectClassName;

    /**
     * 请求头信息，非业务参数
     */
    private Map<String, Object> header;

    /**
     * 类名
     */
    private String className;

    /**
     * 方法名
     */
    private String methodName;

    /**
     * 参数
     */
    private Object[] args;


    /**
     * 接口缓存key
     */
    private String interfaceKey;

    public CacheWrapper() {
    }

    public CacheWrapper(T cacheObject, long lastLoadTime, int expire, Class<?> returnType, List<Long> ids, List<Object> objectList, String objectClassName, Map<String, Object> header, String className, String methodName, Object[] args) {
        this.cacheObject = cacheObject;
        this.lastLoadTime = lastLoadTime;
        this.expire = expire;
        this.returnType = returnType;
        this.ids = ids;
        this.objectList = objectList;
        this.header = header;
        this.className = className;
        this.methodName = methodName;
        this.args = args;
        this.objectClassName = objectClassName;
    }

    public CacheWrapper(T cacheObject, int expire) {
        this.cacheObject = cacheObject;
        this.lastLoadTime = System.currentTimeMillis();
        this.expire = expire;
    }

    public CacheWrapper(T cacheObject, int expire, long lastLoadTime) {
        this.cacheObject = cacheObject;
        this.lastLoadTime = lastLoadTime;
        this.expire = expire;
    }

    /**
     * 判断缓存是否已经过期
     *
     * @return boolean
     */
    public boolean isExpired() {
        if (expire > 0) {
            return (System.currentTimeMillis() - lastLoadTime) > expire * 1000;
        }
        return false;
    }

    @Override
    public Object clone() throws CloneNotSupportedException {
        @SuppressWarnings("unchecked")
        CacheWrapper<T> tmp = (CacheWrapper<T>) super.clone();
//        tmp.setCacheObject(this.cacheObject);
//        tmp.setReturnType(this.returnType);
//        tmp.setHeader(this.header);
//        tmp.setArgs(this.args);
        return tmp;
    }

}
